package com.lanlian.cayman.rabbitmq;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.ShutdownListener;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * <pre>
 *     author : huxiaobo
 *     e-mail : huxiaobo@xlanlian.com
 *     date   : 2018/8/20 15:15
 *     desc   : MQ连接池
 *     version: 1.0
 * </pre>
 */
public abstract class MQConnector {

    protected Channel mChannel = null;
    protected Connection mConnection;

    protected String host;
    protected int port;
    protected String username;
    protected String password;

    public MQConnector(String host, String username, String password, int port) {
        this.host = host;
        this.username = username;
        this.password = password;
        this.port = port;
    }

    /**
     * 关闭所有连接
     *
     * @throws IOException      IO异常
     * @throws TimeoutException 超时异常
     */
    public void closeMQConnection() throws IOException, TimeoutException {
        if (isConnected()) {
            mConnection.close();
        }
        if (isChannelAvailable()) {
            mChannel.close();
            mChannel.abort();
        }
        mConnection = null;
        mChannel = null;
    }

    /**
     * 建立连接
     *
     * @throws IOException      IO异常
     * @throws TimeoutException 超时异常
     */
    protected void createConnection() throws IOException, TimeoutException {
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setUsername(username);
        connectionFactory.setPassword(password);
        connectionFactory.setHost(host);
        connectionFactory.setPort(port);
        mConnection = connectionFactory.newConnection();
        mConnection.addShutdownListener(createShutDownListener());
    }

    /**
     * 创建通道
     */
    protected void createChannel() {
        try {
            mChannel = this.mConnection.createChannel();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 创建关闭监听
     *
     * @return 关闭监听
     */
    protected abstract ShutdownListener createShutDownListener();

    /**
     * 连接是否可用
     *
     * @return 可用/不可用
     */
    public boolean isConnected() {
        return mConnection != null && mConnection.isOpen();
    }

    /**
     * 通道是否可用
     *
     * @return 可用/不可用
     */
    public boolean isChannelAvailable() {
        return mChannel != null && mChannel.isOpen();
    }

}
